#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#define MAXLINE 1024

// exercise 1.3
extern int errno;

int main(int argc, char **argv)
{
	struct sockaddr_in cliaddr;
	int sockfd, socklen, n;
	int tmp;

	char buf[MAXLINE + 1];
	if (argc < 2)
	{
		printf("usage: a.out IP Address\n");
		exit(-1);
	}

	bzero(&cliaddr, sizeof(cliaddr));
	cliaddr.sin_family = AF_INET;
	cliaddr.sin_port = htons(9999);
	
	if (inet_pton(AF_INET, argv[1], &cliaddr.sin_addr) <= 0)
	{
		perror("inet_pton");
		exit(-1);
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("sockfd");
		exit(-1);
	}

	socklen = sizeof(cliaddr);
	if (connect(sockfd, (struct sockaddr *)&cliaddr, socklen) < 0) 
	{
		tmp = errno;
		perror("connect:");
		printf("errno=%d\n", tmp);
		exit(-1);
	}

	while ((n = read(sockfd, buf, MAXLINE)) > 0)
	{
		buf[n] = 0;
		if (fputs(buf, stdout) == EOF)
		{
			perror("fputs");
			exit(-1);
		}
	}

	if (n < 0)
	{
		perror("read");
		exit(-1);
	}
	
	exit(0);

}
